package cn.workreport.modules.cascade.service.imp;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.workreport.modules.cascade.dto.CascadeDTO;
import cn.workreport.modules.cascade.entity.CascadeEntity;
import cn.workreport.modules.cascade.entity.CascadeRelationEntity;
import cn.workreport.modules.cascade.mapper.CascadeMapper;
import cn.workreport.modules.cascade.mapper.CascadeRelationMapper;
import cn.workreport.modules.cascade.service.ICascadeService;
import cn.workreport.modules.cascade.vo.CascadeVO;
import cn.workreport.modules.common.exception.ServiceException;
import cn.workreport.modules.common.vo.PageVO;
import cn.workreport.modules.users.entity.UserEntity;
import cn.workreport.util.JsonResult;
import cn.workreport.util.UserChacheFromToken;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class CascadeServiceImp extends ServiceImpl<CascadeMapper, CascadeEntity> implements ICascadeService {

    @Autowired
    private CascadeRelationMapper cascadeRelationMapper;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public JsonResult<?> saveCascade(CascadeDTO cascadeDTO) {
        String name = cascadeDTO.getName();
        Integer orderNumber = cascadeDTO.getOrderNumber();
        Integer parentId = cascadeDTO.getParentId();
        Integer childrenId = cascadeDTO.getChildrenId();
        Integer orgId = cascadeDTO.getOrgId();
        if (ObjectUtil.isEmpty(orgId)) {
            return JsonResult.fail("参数 orgId 不能为空");
        }
        if (StrUtil.isBlank(name)) {
            return JsonResult.fail("名称不能为空！");
        }
        // 检查是否已经存在此数据
        CascadeVO findDuplicateCascade = baseMapper.findOne(name, parentId, childrenId);
        if (findDuplicateCascade != null) {
            return JsonResult.fail("该条数据已经存在！");
        }

        // 取出当前登录用户信息
        UserEntity currentLoginUser = UserChacheFromToken.getUser();
        Date now = new Date();

        // 将数据插入级联表
        CascadeEntity cascadeEntity = new CascadeEntity();
        cascadeEntity.setName(name);
        cascadeEntity.setOrgId(orgId);
        // 若排序编号没填，自动在最大的加10
        if (orderNumber == null) {
            Integer maxOrderNumber = baseMapper.findMaxOrderNumberByParentId(parentId);
            log.info("maxOrderNumber ===>" + maxOrderNumber);

            // 如果该业务名称下没有数据，则设置初始排序值为 10
            if (maxOrderNumber == null) {
                cascadeEntity.setOrderNumber(10);
            }
            // 否则在最大值基础上再加 10
            else {
                cascadeEntity.setOrderNumber(maxOrderNumber + 10);
            }
        } else {
            cascadeEntity.setOrderNumber(orderNumber);
        }
        log.info("cascadeEntity ==>" + cascadeEntity);
        if (currentLoginUser != null) {
            cascadeEntity.setCreatorId(currentLoginUser.getId());
            cascadeEntity.setCreatorName(currentLoginUser.getUsername());
            cascadeEntity.setCreatedTime(now);
        }
        // 执行插入数据操作
        Integer rows = baseMapper.insertCascade(cascadeEntity);

        // 将数据插入级联表关系表
        CascadeRelationEntity cascadeRelationEntity = new CascadeRelationEntity();
        cascadeRelationEntity.setCascadeId(cascadeEntity.getId());
        cascadeRelationEntity.setParentId(parentId);
        log.info("cascadeRelationEntity ==>" + cascadeRelationEntity);
        if (currentLoginUser != null) {
            cascadeRelationEntity.setCreatorId(currentLoginUser.getId());
            cascadeRelationEntity.setCreatorName(currentLoginUser.getUsername());
            cascadeRelationEntity.setCreatedTime(now);
        }
        rows += cascadeRelationMapper.insertCascadeRelation(cascadeRelationEntity);

        // 修改父级的 childrenId , 改为子级的id
        if (parentId != null) {
            Integer rows2 = cascadeRelationMapper.updateChildrenIdById(parentId, cascadeEntity.getId());
            System.err.println("\trows2 =>" + rows2);
        }

        if (rows >= 2) {
            return JsonResult.ok();
        } else {
            throw new ServiceException("执行失败");
        }
    }

    @Override
    public List<CascadeVO> listCascade(Integer orgId, Integer parentId) {
        // parentId 可以为空，为空时，查询的是顶级
        List<CascadeVO> cascadeVOArrayList = baseMapper.findListByParentId(orgId, parentId);
        return cascadeVOArrayList;
    }

    @Override
    public JsonResult<?> listTree(Integer orgId) {
        if (ObjectUtil.isEmpty(orgId)) {
            return JsonResult.fail("参数 orgId 不能为空");
        }
        List<CascadeVO> orgCascadeList = baseMapper.listByOrgId(orgId);
        List<CascadeVO> rootCascadeList = baseMapper.findListByParentId(orgId, null);
        if (ObjectUtil.isNotEmpty(rootCascadeList)) {
            for (CascadeVO cascade : rootCascadeList) {
                List<CascadeVO> childrenList = getCascadeList(orgCascadeList, cascade);
                cascade.setChildren(childrenList);
            }
        }
        return JsonResult.ok(rootCascadeList);
    }

    @Override
    public List<CascadeVO> listAll(Integer orgId) {
        if (ObjectUtil.isEmpty(orgId)) {
            return new ArrayList<>();
        }
        return baseMapper.listByOrgId(orgId);
    }

    private List<CascadeVO> getChildrenList(List<CascadeVO> parentList, Integer parentId) {
        if (ObjectUtil.isNotEmpty(parentList)) {
            List<CascadeVO> childrenList = parentList.stream().filter(item -> {
                if (ObjectUtil.isEmpty(parentId)) {
                    return ObjectUtil.isEmpty(item.getParentId());
                }
                return parentId.equals(item.getParentId());
            }).collect(Collectors.toList());
            return childrenList;
        } else {
            return new ArrayList<>();
        }
    }

    private List<CascadeVO> getCascadeList(List<CascadeVO> parentList, CascadeVO cascade) {
        List<CascadeVO> childrenList = this.getChildrenList(parentList, cascade.getId());
        if (ObjectUtil.isNotEmpty(childrenList)) {
            for (CascadeVO child : childrenList) {
                List<CascadeVO> grandChildrenList = getCascadeList(parentList, child);
                child.setChildren(grandChildrenList);
            }
        }
        return childrenList;
    }

    @Override
    public void wrapEntity(CascadeEntity entity) {

    }

    @Override
    public PageVO pageEntity(IPage<CascadeEntity> page, Wrapper<CascadeEntity> queryWrapper) {
        return null;
    }

    @Override
    public CascadeEntity getByIdEntity(Integer id) {
        return null;
    }

    @Override
    public JsonResult saveOrUpdateEntity(CascadeEntity entity) {
        return null;
    }

    @Override
    public JsonResult removeByIdEntity(Integer id) {
        CascadeVO cascadeVO = baseMapper.findOneById(id);
        if (ObjectUtil.isEmpty(cascadeVO)) {
            return JsonResult.fail("要删除的数据已不存在");
        }
        // 删除对应关系
        if (ObjectUtil.isNotEmpty(cascadeVO.getParentId())) {
            cascadeRelationMapper.clearChildrenRelationByCascadeId(id);
        }
        cascadeRelationMapper.deleteCascadeRelationByCascadeId(id);
        if (baseMapper.deleteCascadeById(id) <= 0) {
            return JsonResult.fail("删除失败3");
        }
        return JsonResult.ok();
    }

    @Override
    public JsonResult removeByIdsEntity(List<Integer> ids) {
        return null;
    }
}
